import sdk from '../core';
import { wordMap, wordCell } from "../core/rpg/wordMap";
import { analysisIntent } from "../core/tool/baseScene";
import enemy from "../core/rpg/entity/enemy";
import { 道具枚举, ItemType, quality } from "../shared/face/enums";
import { BattleArea } from "../core/rpg/battleArea";
import { Icard } from "../core/tool/Icard";
import common from "../core/tool/common";
import { ComType } from "../core/tool/component";
import { TaskTargetType } from '../core/rpg/types/task';
import { TaskService } from './TaskService';
import { BattleCore } from '../core/rpg';
import create_component from '../component/create_component';

/**
 * 位置服务类
 * 职责：
 * 1. 地图和位置管理
 * 2. 移动逻辑处理
 * 3. 探索功能
 * 4. 战斗创建和管理
 * 5. 侦察和捕捉功能
 */
export class PositionService {

    /**
     * 获取位置信息
     * @param map 地图对象
     * @param player 玩家对象
     * @returns 位置信息卡片
     */
    static getPositionInfo(map: wordMap, player: any): {
        success: boolean;
        message: string;
        card?: Icard;
    } {
        if (!map) {
            return {
                success: false,
                message: '地图未初始化'
            };
        }

        try {
            const card = map.client_getPosition(player);
            return {
                success: true,
                message: '获取位置信息成功',
                card
            };
        } catch (error) {
            return {
                success: false,
                message: '获取位置信息失败'
            };
        }
    }

    /**
     * 移动到指定方向
     * @param map 地图对象
     * @param player 玩家对象
     * @param direction 移动方向
     * @returns 移动结果
     */
    static moveToDirection(map: wordMap, player: any, direction: string): {
        success: boolean;
        message: string;
        newPosition?: any;
    } {
        if (!map) {
            return {
                success: false,
                message: '地图未初始化'
            };
        }

        try {
            const result = map.move(player, direction);
            
            // 更新世界任务进度（移动也算探索）
            const taskComponent = player.getComponent(ComType.任务) as any;
            if (taskComponent) {
                taskComponent.updateWorldTaskProgress(player, TaskTargetType.探索);
            }
            
            return {
                success: true,
                message: `移动到${direction}方向成功`,
                newPosition: result
            };
        } catch (error) {
            return {
                success: false,
                message: `移动到${direction}方向失败`
            };
        }
    }

    /**
     * 探索当前位置
     * @param map 地图对象
     * @param player 玩家对象
     * @returns 探索结果
     */
    static exploreCurrentPosition(map: wordMap, player: any): {
        success: boolean;
        message: string;
        exploreResult?: any;
    } {
        if (!map) {
            return {
                success: false,
                message: '地图未初始化'
            };
        }

        try {
            const result = map.explore(player);
            
            // 更新任务进度
            TaskService.updateTaskProgress(player, TaskTargetType.探索);
            
            // 更新世界任务进度
            const taskComponent = player.getComponent(ComType.任务) as any;
            if (taskComponent) {
                taskComponent.updateWorldTaskProgress(player, TaskTargetType.探索);
            }
            
            return {
                success: true,
                message: '探索完成',
                exploreResult: result
            };
        } catch (error) {
            return {
                success: false,
                message: '探索失败'
            };
        }
    }

    /**
     * 侦察指定目标
     * @param cell 当前格子
     * @param targetIndex 目标索引
     * @returns 侦察结果
     */
    static spyTarget(cell: wordCell, targetIndex: number): {
        success: boolean;
        message: string;
        target?: any;
    } {
        if (!cell) {
            return {
                success: false,
                message: '当前位置无效'
            };
        }

        const target = cell.getCellByIndex(targetIndex);
        if (!target) {
            return {
                success: false,
                message: '侦察目标不存在'
            };
        }

        return {
            success: true,
            message: '侦察成功',
            target
        };
    }

    /**
     * 捕捉目标
     * @param cell 当前格子
     * @param targetIndex 目标索引
     * @param bagItems 背包物品
     * @returns 捕捉结果
     */
    static captureTarget(cell: wordCell, targetIndex: number, bagItems: any[]): {
        success: boolean;
        message: string;
        capturedItem?: any;
        requiredItems?: any[];
    } {
        if (!cell) {
            return {
                success: false,
                message: '当前位置无效'
            };
        }

        const target = cell.getCellByIndex(targetIndex);
        if (!target) {
            return {
                success: false,
                message: '捕捉目标不存在'
            };
        }

        if (!(target instanceof enemy)) {
            return {
                success: false,
                message: '无法捕捉的单位'
            };
        }

        const rpgCom = target.getComponent(ComType.rpg);
        if (rpgCom.isDie()) {
            return {
                success: false,
                message: '单位已死亡'
            };
        }

        // 检查是否有精灵球
        const requiredItems = [{ key: 道具枚举.精灵球, val: 1, type: ItemType.道具 }];
        
        // 这里简化检查，实际应该调用背包的验证方法
        const hasPokeball = bagItems.some(item => 
            item.type === ItemType.道具 && item.id === 道具枚举.精灵球 && item.count >= 1
        );

        if (!hasPokeball) {
            return {
                success: false,
                message: '缺少精灵球',
                requiredItems
            };
        }

        try {
            const createData = (target.getComponent(ComType.创建数据) as create_component).get_create_data();
            const capturedItem = sdk.prop.createProp_customize({
                type: ItemType.消耗品,
                id: sdk.tool.common.uuid,
                tag: '宠物蛋',
                count: 1,
                uuid: sdk.tool.common.uuid,
                emoji: '🐶',
                icon: '',
                quality: quality.SSR,
                name: '宠物蛋',
                desc: `使用后可孵化宠物${createData.emoji}${createData.name}`,
                stacking: false,
                stacking_use: false,
                data: {
                    funcName: 'AddPet',
                    funcData: createData
                },
            });
            // 击杀目标
            rpgCom.kill();

            return {
                success: true,
                message: `捕捉成功！${capturedItem.emoji}${capturedItem.name} - 已放入背包`,
                capturedItem,
                requiredItems
            };
        } catch (error) {
            return {
                success: false,
                message: '捕捉失败'
            };
        }
    }

    /**
     * 验证地图是否可用
     * @param map 地图对象
     * @returns 验证结果
     */
    static validateMap(map: wordMap): {
        isValid: boolean;
        message: string;
    } {
        if (!map) {
            return {
                isValid: false,
                message: '地图未初始化'
            };
        }

        return {
            isValid: true,
            message: '地图可用'
        };
    }

    /**
     * 获取可用的移动方向
     * @param map 地图对象
     * @param player 玩家对象
     * @returns 可用的移动方向
     */
    static getAvailableDirections(map: wordMap, player: any): {
        success: boolean;
        directions: string[];
    } {
        if (!map) {
            return {
                success: false,
                directions: []
            };
        }

        // 基础方向
        const basicDirections = ['上', '下', '左', '右'];
        
        // 这里可以添加更复杂的逻辑来检查哪些方向可以移动
        return {
            success: true,
            directions: basicDirections
        };
    }

    /**
     * 获取当前位置的统计信息
     * @param cell 当前格子
     * @returns 位置统计信息
     */
    static getPositionStats(cell: wordCell): {
        success: boolean;
        stats: {
            totalUnits: number;
            enemyCount: number;
            allyCount: number;
            itemCount: number;
        };
    } {
        if (!cell) {
            return {
                success: false,
                stats: {
                    totalUnits: 0,
                    enemyCount: 0,
                    allyCount: 0,
                    itemCount: 0
                }
            };
        }

        // 这里需要根据实际的cell结构来实现统计逻辑
        const stats = {
            totalUnits: 0,
            enemyCount: 0,
            allyCount: 0,
            itemCount: 0
        };

        return {
            success: true,
            stats
        };
    }
} 